class User < ActiveRecord::Base
  acts_as_authentic
  acts_as_tagger
  has_and_belongs_to_many :roles
  has_many :votes
  has_many :voted_on_thoughts, :through => :votes, :source => :thought

  def vote_on(thought_id, vote_value)
    return recant_vote_for(thought_id) if vote_value == 0
    @vote = unless self.votes.exists?(:thought_id => thought_id)
      self.votes.create(:thought_id => thought_id, :value => vote_value)
    else
      v = self.votes.find(:first, :conditions => {:thought_id => thought_id})
      v.value = vote_value
      v
    end
    @vote.save
    Thought.find(thought_id).tally_votes
    @vote  
  end

  def recant_vote_for(thought_id)
    return false unless votes.exists?(:thought_id => thought_id)
    @vote = votes.find(:first, :conditions => {:thought_id => thought_id})
    votes.delete!(@vote)
    save
    Thought.find(thought_id).tally_votes
  end

  def has_voted_on?(thought_id)
    return false unless votes.exists?(:thought_id => thought_id)
    @vote = votes.find(:first, :conditions => {:thought_id => thought_id})
    @vote.value != 0
  end
end
